package com.ruicar.afs.cloud.apply.pre.loan.service.impl;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.apply.common.dto.ChannelInfoDTO;
import com.ruicar.afs.cloud.apply.common.entity.ApplyChannelInfo;
import com.ruicar.afs.cloud.apply.common.feign.Apply2ChannelFeign;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConfig;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyReportCondition;
import com.ruicar.afs.cloud.apply.pre.loan.condition.CarDealerCondition;
import com.ruicar.afs.cloud.apply.pre.loan.mapper.ApplyChannelInfoMapper;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyChannelInfoService;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 申请渠道信息
 * @author: sijun.yu
 * @date: 2020/6/23 0:04
 */
@Service
@AllArgsConstructor
public class ApplyChannelInfoServiceImpl extends ServiceImpl<ApplyChannelInfoMapper, ApplyChannelInfo> implements ApplyChannelInfoService {

    private Apply2ChannelFeign channelFeign;
    private ApplyConfig config;

    /**
     * 通过申请编号获取渠道信息
     *
     * @param applyNo
     * @return
     */
    public ApplyChannelInfo getChannelInfoByApplyNo(String applyNo) {

        ApplyChannelInfo applyChannelInfo = this.baseMapper.selectOne(Wrappers.<ApplyChannelInfo>query().lambda()
                .eq(ApplyChannelInfo::getApplyNo, applyNo));
        return applyChannelInfo;
    }

    /**
     * 获取产品请求头
     *
     * @return
     */
    public Map makeCaseHeader() {
        Map<String, String> headers = new HashMap<>();
        headers.put("clientId", config.getCaseClientId());
        headers.put("clientSecret", config.getCaseClientSecret());
        return headers;
    }

    /**
     * 查询车商列表
     *
     * @return
     */
    public IResponse getCarDealList(CarDealerCondition condition) {

        ChannelInfoDTO dto = new ChannelInfoDTO();
        dto.setUserId(condition.getUserId());
        dto.setCardealerType(condition.getCardealerType());
        dto.setChannelId(condition.getChannelId());
        dto.setBusinessType(condition.getBusinessType());
        return channelFeign.getCarDealList(dto, this.makeCaseHeader());
    }

    /**
     * 查询挂靠公司列表
     *
     * @param condition
     * @return
     */
    public IResponse getAffiliatedUnitsList(CarDealerCondition condition) {

        ChannelInfoDTO dto = new ChannelInfoDTO();
        dto.setChannelId(condition.getChannelId());
        dto.setAffiliatedType(condition.getAffiliatedType());
        dto.setAffUnitsName(condition.getAffUnitsName());
        return channelFeign.getAffiliatedUnitsList(dto, this.makeCaseHeader());
    }

    /**
     * 查询网约车平台列表
     *
     * @param condition
     * @return
     */
    public IResponse getCooperPlatList(CarDealerCondition condition) {

        ChannelInfoDTO dto = new ChannelInfoDTO();
        dto.setSocUniCrtCode(condition.getSocUniCrtCode());
        return channelFeign.getCooperPlatList(dto, this.makeCaseHeader());
    }

    /**
     * 获取渠道车辆类型
     * @param condition
     * @return
     */
    public List<String> queryCarType(ApplyReportCondition condition){

        ChannelInfoDTO dto = new ChannelInfoDTO();
        if(StringUtil.isNotBlank(condition.getDealerId())){
            dto.setChannelId(condition.getDealerId());
        }else{
            dto.setChannelId(SecurityUtils.getUser().getUserExtInfo().getJSONObject("channelInfo").getString("channelId"));
        }
        dto.setBusinessType(condition.getBusinessType());
        JSONObject jsonObject = channelFeign.queryCarType(dto,this.makeCaseHeader());
        String[] carTypes = jsonObject.getString("data").split(",");
        List<String> list = Arrays.asList(carTypes);
        return list;
    }

    /**
     * 通过渠道ID获取渠道信息
     *
     * @param channelId
     * @return
     */
    public JSONObject getChannelDetailInfo(String channelId) {

        ChannelInfoDTO dto = new ChannelInfoDTO();
        dto.setChannelId(channelId);
        return channelFeign.getChannelDetailInfo(dto, this.makeCaseHeader());
    }

    /**
     * 通过渠道id返回渠道和车商列表
     * @param channelId
     * @return
     */
    public IResponse getCarDealerByChannelId(String channelId){

        ChannelInfoDTO dto = new ChannelInfoDTO();
        dto.setChannelId(channelId);
        return channelFeign.getCarDealerByChannelId(dto,makeCaseHeader());
    }

    /**
     * 保存渠道信息
     *
     * @param applyNo
     * @return
     */
    public ApplyChannelInfo saveChannelInfo(String applyNo, ApplyReportCondition condition) {

        ApplyChannelInfo channelInfo = new ApplyChannelInfo();
        channelInfo.setApplyNo(applyNo);
        JSONObject object = SecurityUtils.getUser().getUserExtInfo().getJSONObject("channelInfo");
        String channelId = object.getString("channelId");
        channelInfo.setChannelId(channelId);
        channelInfo.setChannelName(object.getString("channelFullName"));
        channelInfo.setChannelCode(object.getString("channelCode"));

        // 渠道信息
        JSONObject jsonObject = this.getChannelDetailInfo(channelId);
        if (CommonConstants.SUCCESS.equals(jsonObject.getString("code"))) {
            if (jsonObject.getJSONObject("data").getJSONObject("channelBaseInfo") != null) {
                JSONObject channelBaseInfo = jsonObject.getJSONObject("data").getJSONObject("channelBaseInfo");
                String channelBelong = channelBaseInfo.getString("channelBelong");
                channelInfo.setChannelBelong(channelBelong);
                if (ApplyConstants.CHANNEL_BELONG_SP.equals(channelBelong) || ApplyConstants.CHANNEL_BELONG_TOTAl.equals(channelBelong)) {
                    channelInfo.setOrdinaryCarDealersId(condition.getDealerId());
                    channelInfo.setOrdinaryCarDealersName(condition.getDealerName());
                } else if (ApplyConstants.CHANNEL_BELONG_DIRECT.equals(channelBelong)) {
                    channelInfo.setDirectCarDealersId(condition.getDealerId());
                    channelInfo.setDirectCarDealersName(condition.getDealerName());
                }
                JSONArray riskList = jsonObject.getJSONObject("data").getJSONArray("risk");
                if (riskList != null && riskList.size() > 0) {
                    for (int i = 0; i < riskList.size(); i++) {
                        String businessType = riskList.getJSONObject(i).getString("businessType");
                        // 新车
                        if (ApplyConstants.BUSINESS_TYPE_NEW_CAR.equals(businessType) && ApplyConstants.BUSINESS_TYPE_NEW_CAR.equals(condition.getBusinessType())) {
                            channelInfo.setChannelGrade(riskList.getJSONObject(i).getString("channelGrade"));
                            channelInfo.setQualityGrade(riskList.getJSONObject(i).getString("qualityGrade"));
                            channelInfo.setCustomerManager(riskList.getJSONObject(i).getString("customerManager"));
                        }
                        // 二手车
                        else if (ApplyConstants.BUSINESS_TYPE_OLD_CAR.equals(businessType) && ApplyConstants.BUSINESS_TYPE_OLD_CAR.equals(condition.getBusinessType())) {
                            channelInfo.setChannelGrade(riskList.getJSONObject(i).getString("channelGrade"));
                            channelInfo.setQualityGrade(riskList.getJSONObject(i).getString("qualityGrade"));
                            channelInfo.setCustomerManager(riskList.getJSONObject(i).getString("customerManager"));
                        }
                    }
                }
                channelInfo.setChannelProvince(channelBaseInfo.getString("channelProvince"));// 省份
                channelInfo.setChannelCity(channelBaseInfo.getString("channelCity"));// 城市
                // add sijun.yu 2020-8-31 获取收款账号数据
                JSONArray acountList = jsonObject.getJSONObject("data").getJSONArray("acount");
                if(acountList!=null && acountList.size()>0){
                    for (int j = 0;j < acountList.size(); j++){
                        String accountAttribute = acountList.getJSONObject(j).getString("accountAttribute");
                        String collectionType = acountList.getJSONObject(j).getString("collectionType");// 1-车款
                        if("1".equals(collectionType) && accountAttribute!=null && accountAttribute.equals(condition.getBusinessType())){
                            channelInfo.setReceiptBankCode(acountList.getJSONObject(j).getString("receivingBank"));
                            channelInfo.setReceiptAccount(acountList.getJSONObject(j).getString("receivingAccount"));
                            channelInfo.setReceiptName(acountList.getJSONObject(j).getString("receivingName"));
                        }
                    }
                }
            }
        }
        this.baseMapper.insert(channelInfo);

        return channelInfo;
    }

    /**
     * 更新渠道信息
     *
     * @param channelInfo
     * @param condition
     * @return
     */
    public void updateChannelInfo(ApplyChannelInfo channelInfo, ApplyReportCondition condition) {

        String channelBelong = channelInfo.getChannelBelong();
        if (ApplyConstants.CHANNEL_BELONG_SP.equals(channelBelong) || ApplyConstants.CHANNEL_BELONG_TOTAl.equals(channelBelong)) {
            channelInfo.setOrdinaryCarDealersId(condition.getDealerId());
            channelInfo.setOrdinaryCarDealersName(condition.getDealerName());
        } else if (ApplyConstants.CHANNEL_BELONG_DIRECT.equals(channelBelong)) {
            channelInfo.setDirectCarDealersId(condition.getDealerId());
            channelInfo.setDirectCarDealersName(condition.getDealerName());
        }
        this.baseMapper.updateById(channelInfo);
    }
}
